package P131_CyclicBarrier;

import org.junit.experimental.theories.Theories;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;

/**
 * Desc:&emsp;&ensp;CyclicBarrier让多线程齐步走
 * 多线程汇聚一一点
 *
 * @author 李渊&emsp;liyuan7@yusys.com.cn
 * @version 1.0
 * @since V4.3&emsp;2022/5/20
 */
public class Worker implements Runnable {
    // 关卡
    private CyclicBarrier cb;

    public Worker(CyclicBarrier _cb) {
        cb = _cb;
    }

    @Override
    public void run() {

        try {
            Thread.sleep(new Random().nextInt(1000));
            System.out.println(Thread.currentThread().getName() + "-到达汇合点！");
            cb.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        CyclicBarrier cb = new CyclicBarrier(2, new Runnable() {
            @Override
            public void run() {
                System.out.println("隧道已经打通！");
            }
        });
        new Thread(new Worker(cb), "工人1").start();
        new Thread(new Worker(cb), "工人2").start();
    }
}
